from flask import Flask, jsonify
import paramiko
import configparser
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 添加CORS插件

config = configparser.ConfigParser()
config.read('config.ini')

server_ip = config.get('server', 'ip')
username = config.get('server', 'username')
password = config.get('server', 'password')

# SSH 登录的配置
ssh_config = {
    'hostname': server_ip,
    'port': 22,
    'username': username,
    'password': password
}


# 获取内存信息的接口
@app.route('/memory', methods=['GET'])
def get_memory():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(**ssh_config)
    stdin, stdout, stderr = client.exec_command('free -m | awk \'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)", $3,$2,$3*100/$2 }\'')
    output = stdout.read().decode('utf-8')
    client.close()
    return jsonify({'code': 200, 'msg': output})


# 获取 CPU 信息的接口
@app.route('/cpu', methods=['GET'])
def get_cpu():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(**ssh_config)
    stdin, stdout, stderr = client.exec_command('top -bn1 | grep load | awk \'{printf "CPU Load: %.2f", $(NF-2)}\'')
    output = stdout.read().decode('utf-8')
    client.close()
    return jsonify({'code': 200, 'msg': output})


# 获取硬盘信息的接口
@app.route('/disk', methods=['GET'])
def get_disk():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(**ssh_config)
    stdin, stdout, stderr = client.exec_command('df -h | awk \'$NF=="/"{printf "Disk Usage: %d/%dGB (%s)", $3,$2,$5}\'')
    output = stdout.read().decode('utf-8')
    client.close()
    return jsonify({'code': 200, 'msg': output})


if __name__ == '__main__':

    app.run(debug=True)
